<?php

namespace app\common\model;

use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;

class WeChatPaySplit {
    private $mchId; // 商户号
    private $apiKey; // API密钥
    private $certPath; // 证书路径
    private $keyPath; // 私钥路径

    public function __construct($mchId, $apiKey, $certPath, $keyPath) {
        $this->mchId = $mchId;
        $this->apiKey = $apiKey;
        $this->certPath = $certPath;
        $this->keyPath = $keyPath;
    }

    public function ceshi()
    {
        // 设置参数


// 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyInstance = Rsa::from($this->keyPath, Rsa::KEY_TYPE_PRIVATE);

// 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = '2391149D5C0298EE06E79178D6C51D556D824413';

// 从本地文件中加载「微信支付平台证书」(可使用证书下载工具得到），用来验证微信支付应答的签名
        $platformCertificateFilePath = 'file:///path/to/wechatpay/cert.pem';
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

// 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);

// 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid' => $this->mchId,
            'serial' => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs' => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);

// 以 Native 支付为例，发送请求
        $resp = $instance
            ->chain('v3/pay/transactions/native')
            ->post(['json' => [
                'mchid' => '1900006XXX',
                'out_trade_no' => 'native12177525012014070332333',
                'appid' => 'wxdace645e0bc2cXXX',
                'description' => 'Image形象店-深圳腾大-QQ公仔',
                'notify_url' => 'https://weixin.qq.com/',
                'amount' => [
                    'total' => 1,
                    'currency' => 'CNY'
                ],
                //在http请求增加一个Wechatpay-Serial请求头，具体作用可参考：https://pay.weixin.qq.com/doc/v3/merchant/4012154180#5.2-%E5%88%87%E6%8D%A2%E9%AA%8C%E7%AD%BE%E5%92%8C%E5%AE%9E%E7%8E%B0%E5%9B%9E%E8%B0%83%E5%85%BC%E5%AE%B9
                'headers' => [
                    'Wechatpay-Serial' => 'PUB_KEY_ID_0112232134912010000100000000',
                ],
            ]]);
        echo $resp->getBody(), PHP_EOL;
    }


    private function createSign(array $params): string {
        ksort($params);
        $stringA = urldecode(http_build_query($params));
        $stringSignTemp = $stringA . '&key=' . $this->apiKey;
        return strtoupper(md5($stringSignTemp));
    }

    public function splitOrder(array $data) {
        $url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders";

        $data['sp_mchid'] = $this->mchId;
        $data['sign_type'] = 'HMAC-SHA256';
        $data['nonce_str'] = uniqid();
        $data['sign'] = $this->createSign($data);

        $jsonStr = json_encode($data, JSON_UNESCAPED_UNICODE);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $jsonStr,
            CURLOPT_SSLCERT => $this->certPath,
            CURLOPT_SSLKEY => $this->keyPath,
            CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', // 微信CA证书路径
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
    }
}